
import { Controller } from '@/controller';
import { decorator } from '@/tools/fns/decorator';
import { observer } from 'mobx-react';
import * as echarts from 'echarts';
import React from 'react';
import dayjs from 'dayjs';
import * as XLSX from 'xlsx';


const Overview = decorator(observer)(function () {

    const controller = React.useContext(Controller.Context);
    const { data } = controller;
    const chartDomRef = React.useRef<HTMLDivElement>(null);
    const chartNewCustomersRef = React.useRef<HTMLDivElement>(null);
    const chartInstanceRef = React.useRef<echarts.ECharts | null>(null);

    // 汇总每个月的权益金
    const monthlyEquity = React.useMemo(() => {
        const equityList: number[] = [];
        data.equity?.forEach(item => {
            const d = toXlsxDay(item['日期']);
            const m = d.date() >= 26 ? d.month() + 1 : d.month();
            const o = equityList[m] || 0;
            equityList[m] = o + item['权益金'];
        });
        return equityList.map(e => e.toFixed(2));
    }, [data]);

    // 打印每个月的营业额
    const monthlyTurnover = React.useMemo(() => {
        const turnoverList: number[] = [];
        data.turnover?.forEach(item => {
            const d = toXlsxDay(item['日期']);
            const m = d.date() >= 26 ? d.month() + 1 : d.month();
            const o = turnoverList[m] || 0;
            turnoverList[m] = o + item['耗卡金额'];
        });

        // 权益金 的 外卖
        data.equity
            ?.filter(item => item['权益金类型'] === '外卖')
            ?.forEach(item => {
                const d = toXlsxDay(item['日期']);
                const m = d.date() >= 26 ? d.month() + 1 : d.month();
                const o = turnoverList[m] || 0;
                turnoverList[m] = o + item['权益金'];
            });

        return turnoverList.map(e => e.toFixed(2));
    }, [data]);

    // 汇总每个月的新客 
    const monthlyNewCustomers = React.useMemo(() => {
        const newCustomerMap: Map<string, number>[] = [];
        data.turnover?.forEach(item => {
            const d = toXlsxDay(item['日期']);
            const m = d.date() >= 26 ? d.month() + 1 : d.month();
            if (!newCustomerMap[m]) newCustomerMap[m] = new Map();
            if (item['客户类型'] === '新客') newCustomerMap[m].set(item['客户名称'] + d.format('YYYYMMDD'), 1);
        });
        return newCustomerMap.map(e => e.size || 0);
    }, [data]);

    // 汇总每个月的会员
    const monthlyMember = React.useMemo(() => {
        const newCustomerMap: Map<string, number>[] = [];
        data.turnover?.forEach(item => {
            const d = toXlsxDay(item['日期']);
            const m = d.date() >= 26 ? d.month() + 1 : d.month();
            if (!newCustomerMap[m]) newCustomerMap[m] = new Map();
            if (item['客户类型'] === '会员') newCustomerMap[m].set(item['客户名称'] + d.format('YYYYMMDD'), 1);
        });
        return newCustomerMap.map(e => e.size || 0);
    }, [data]);

    // 汇总每个月客次
    const monthlyCustomerVisits = React.useMemo(() => {
        const customerVisitsMap: Map<string, number>[] = [];
        data.turnover?.forEach(item => {
            const d = toXlsxDay(item['日期']);
            const m = d.date() >= 26 ? d.month() + 1 : d.month();
            if (!customerVisitsMap[m]) customerVisitsMap[m] = new Map();
            customerVisitsMap[m].set(item['客户名称'] + d.format('YYYYMMDD'), 1);
        });
        return customerVisitsMap.map(e => e.size || 0);
    }, [data]);

    // '权益金', '营业额'
    React.useEffect(() => {
        // 确保DOM元素存在
        if (chartDomRef.current) {
            // 初始化图表
            const chart = echarts.init(chartDomRef.current);
            chartInstanceRef.current = chart;

            // 设置图表配置
            chart.setOption({
                title: {
                    text: ''
                },
                legend: {
                    data: ['权益金', '营业额']
                },
                tooltip: {},
                xAxis: {
                    data: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
                },
                yAxis: {},
                series: [
                    {
                        name: '权益金',
                        type: 'bar',
                        data: monthlyEquity
                    }, {
                        name: '营业额',
                        type: 'bar',
                        data: monthlyTurnover
                    }
                ]
            });
        }

        // 组件卸载时清理图表实例
        return () => {
            if (chartInstanceRef.current) {
                chartInstanceRef.current.dispose();
                chartInstanceRef.current = null;
            }
        };
    }, [monthlyEquity, monthlyTurnover]);

    // 新客
    React.useEffect(() => {
        // 确保DOM元素存在
        if (chartNewCustomersRef.current) {
            // 初始化图表
            const chart = echarts.init(chartNewCustomersRef.current);
            chartInstanceRef.current = chart;

            // 设置图表配置
            chart.setOption({
                title: {
                    text: ''
                },
                legend: {
                    data: ['新客', '会员', '客次']
                },
                tooltip: {},
                xAxis: {
                    data: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
                },
                yAxis: {},
                series: [
                    {
                        name: '新客',
                        type: 'bar',
                        data: monthlyNewCustomers
                    },
                    {
                        name: '会员',
                        type: 'bar',
                        data: monthlyMember
                    },
                    {
                        name: '客次',
                        type: 'bar',
                        data: monthlyCustomerVisits
                    }
                ]
            });
        }

        // 组件卸载时清理图表实例
        return () => {
            if (chartInstanceRef.current) {
                chartInstanceRef.current.dispose();
                chartInstanceRef.current = null;
            }
        };
    }, [monthlyCustomerVisits, monthlyMember, monthlyNewCustomers]);

    return (
        <div style={{ padding: 20 }} >
            <div ref={chartDomRef} style={{ width: '100%', height: '400px' }} />
            <div ref={chartNewCustomersRef} style={{ width: '100%', height: '400px' }} />
        </div>
    );
})
export default Overview;


function toXlsxDay(params: any) {
    return dayjs(XLSX.SSF.format("yyyy-mm-dd", params))
}